package controller

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"scoce_estimate/config"
	"scoce_estimate/data_process"
	"scoce_estimate/db_connect"
	"scoce_estimate/model"
	"scoce_estimate/status"
	"scoce_estimate/utils/decode"
	"strings"

	"github.com/gin-gonic/gin"
)

type query_result struct {
	Title string
	Score int
}

const ERROR_MESSAGE_WAIT = "正在评估中，请过几分钟再来"
const ERROR_MESSAGE_NOT_EXIST = "准考证号不存在"

func QueryPage(c *gin.Context) {
	raw_user_id := c.Query("user_id")
	// 去空格
	raw_user_id = strings.Replace(raw_user_id, " ", "", -1)
	// 去tap
	raw_user_id = strings.Replace(raw_user_id, "	", "", -1)
	// 统一大写
	raw_user_id = strings.ToUpper(raw_user_id)

	level := c.Query("level")
	user_id := level + raw_user_id
	fmt.Println(user_id)

	data := []query_result{}
	titles := []string{}
	title_map := map[string]int{}
	var level_status int
	fp := ""
	if level == config.Cspj_prefix {
		level_status = status.CSPJ_LEVEL
	} else if level == config.Csps_prefix {
		level_status = status.CSPS_LEVEL
	}
	titles, title_map, fp = config.GetTitleAndMap(level_status)
	err_page := false
	err_message := ""

	for i := 0; i < len(titles); i++ {
		problem_id := title_map[titles[i]]
		res := data_process.GetScore(user_id, problem_id)
		fmt.Println(user_id, res)

		if res.Status == status.NOT_EXIST {
			c.HTML(http.StatusOK, "query_error.html", ERROR_MESSAGE_NOT_EXIST)
			return
		} else if res.Status == status.NOT_IN_QUEUE {
			// TODO
			user := &model.User{User_id: user_id}
			data_process.AddToTQueue(user_id, level_status)
			codePath := fmt.Sprintf("%s/%s/%s/%s.cpp", fp, raw_user_id, titles[i], titles[i])
			source, err := ioutil.ReadFile(codePath)
			if err != nil {
				fmt.Println(err.Error())
			}
			source, err = decode.GbkToUtf8(source)

			if err != nil {
				fmt.Println(err.Error())
			} else {
				db_connect.UploadSolution(user, problem_id, len(source), string(source))
				fmt.Println("Urgent Upload ", user, problem_id)
			}

			err_page = true
			err_message = ERROR_MESSAGE_WAIT

		} else if res.Status == status.IN_QUEUE {
			// TODO
			err_page = true
			err_message = ERROR_MESSAGE_WAIT
		} else if res.Status == status.HAS_RESULT {
			data = append(data, query_result{titles[i], res.Score})
		}

	}

	if err_page {
		c.HTML(http.StatusOK, "query_error.html", err_message)
		return
	}

	total := data_process.GetTotal(user_id, titles, title_map)
	ranking := data_process.GetRanking(total, level_status)
	var overall_total int = 0
	if level_status == status.CSPJ_LEVEL {
		overall_total = data_process.GetCSPJTotal()
	} else if level_status == status.CSPS_LEVEL {
		overall_total = data_process.GetCSPSTotal()
	}
	c.HTML(http.StatusOK, "query.html", gin.H{"data": data, "user_id": raw_user_id, "ranking": ranking, "overall_total": overall_total})
}
